package com.aiyige.page.my.buy;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ModuleEngine;
import com.aiyige.model.Subject;
import com.aiyige.model.SummaryUserResourse;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.resource.UserResource;
import com.aiyige.page.my.buy.adapter.SearchMyBuyAdapter;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.MyEditText;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by xiachao on 2018/5/7
 */
@Route(path = ARouterConfig.SearchMyBuyPage)
public class SearchMyBuyPage extends BaseActivity {

    private static final String TAG = "SearchMyBuyPage";

    public static final int HANDLE_SEARCH = 1;

    @BindView(R.id.cdv)
    CommonDataView cdv;

    SearchMyBuyAdapter adapter;

    @BindView(R.id.et_search)
    MyEditText inputEt;

    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @BindView(R.id.cancelLayout)
    ExpandableLayout cancelLayout;

//    TextWatcher searchTextWatcher;

    HandlerThread searchThread;
    Handler searchHandler;
    Handler mainHandler;

    @Autowired
    public String keyWord;

    public static void start(String keyWord) {
        ARouter.getInstance().build(ARouterConfig.SearchMyBuyPage).withString("keyWord", keyWord).navigation();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_search_my_favorites);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initViews();
    }

    private void initViews() {
        adapter = new SearchMyBuyAdapter();
        cdv.config(adapter, null);
        cdv.doRefreshRequest();
        cdv.addItemDecoration(1, R.color.zwcolor_gray_e3e3e3);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(this, R.color.zwcolor_gray_f4f8f9));
        inputEt.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSearchResultPanel();
                }
            }
        });

        adapter.setSearchValueCallback(new SearchMyBuyAdapter.SearchValueCallback() {
            @Override
            public String getSearchValue() {
                return inputEt.getEditText().getText().toString().trim();
            }
        });
        inputEt.setActionSearch(new MyEditText.ActionCallback() {
            @Override
            public void actionSearch(String value) {
                doSearch(value);
            }
        });
        inputEt.setEditTextHint(getString(R.string.search));
        searchThread = new HandlerThread(TAG + "SearchThread");
        searchThread.start();
        mainHandler = new Handler(Looper.getMainLooper());
        searchHandler = new Handler(searchThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        try {
                            if (isEmpty(getSearchValue())) {
                                return;
                            }
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    cdv.showLoadingLayout();
                                }
                            });
//                            String json =  MyFavoriteSearchRequest.newBuilder().keyWord(getSearchValue()).build().execute().body().string();
                            final Response<ResponseBody> response = ApiManager.getService()
                                    .seachFavoriteSummary(ModuleEngine.USER_RESOURCE, getSearchValue(),null)
                                    .execute();
                            if (response.code() != ResponseCode.OK) {
                                try {
                                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            String json = null;
                            try {
                                json = RetrofitUtil.getResponseBodyAsString(response);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            final SummaryUserResourse summary = JsonUtil.toObject(json, SummaryUserResourse.class);
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    cdv.hideCoverLayout();
                                }
                            });
                            if (isEmpty(json)) {
                                return;
                            }

                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.setNewData(getTypeList(summary));
                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        break;
                    default:
                        break;
                }
            }
        };
//        inputEt.performClick();
        if (!isEmpty(keyWord)) {
            inputEt.getEditText().setText(keyWord);
//            AppUtils.showSoftInputFromWindow(this,inputEt.getEditText());
            doSearch(keyWord);
        }
    }

    private List<UserResource> getTypeList(SummaryUserResourse summary) {
        if (summary == null) {
            return null;
        }
        List<UserResource> list = new ArrayList<>();
        // 遍历教学视频
        if (summary.getVideoCourse() != null && !summary.getVideoCourse().isEmpty()) {
            UserResource userResource  = null;
            for (int i = 0; i < summary.getVideoCourse().size(); i++) {
                if (i == 4) {
                    break;
                }
                userResource = summary.getVideoCourse().get(i);
                if (userResource != null && !ListUtil.isEmpty(userResource.getResourceBackup())) {
                    try{
                        summary.getVideoCourse().get(i).getResourceBackup().get(0).setTitle(HighLightWordUtil.highLight(summary.getVideoCourse().get(i).getResourceBackup().get(0).getTitle(),keyWord));
                    }catch (Exception e){

                    }
                    userResource.setShowTitle(i == 0);
                    userResource.setHasMore(summary.getVideoCourseCount() > 4);
                    list.add(userResource);
                }
            }
        } else {
            UserResource searchTypeMoment = new UserResource();
            Moment moment = new Moment();
            moment.setSubject(Subject.video_course);
            searchTypeMoment.setResourceBackup(Arrays.asList(moment));
            searchTypeMoment.setShowTitle(true);
            list.add(searchTypeMoment);
        }

        // 遍历专业课程
        if (summary.getMajorCourse() != null && !summary.getMajorCourse().isEmpty()) {
            UserResource userResource  = null;
            for (int i = 0; i < summary.getMajorCourse().size(); i++) {
                if (i == 4) {
                    break;
                }
                userResource = summary.getMajorCourse().get(i);
                Moment majorCourseMoment =  userResource != null && !ListUtil.isEmpty(userResource.getResourceBackup())?summary.getMajorCourse().get(i).getResourceBackup().get(0):null;
                if (majorCourseMoment != null) {
                    try{
                        majorCourseMoment.setTitle(HighLightWordUtil.highLight(majorCourseMoment.getTitle(),keyWord));
                    }catch (Exception e){

                    }
                    userResource.setShowTitle(i == 0);
                    userResource.setHasMore(summary.getMajorCourseCount() > 4);
                    list.add(userResource);
                }
            }
        } else {
            UserResource searchTypeMoment = new UserResource();
            Moment moment = new Moment();
            moment.setSubject(Subject.major_course);
            searchTypeMoment.setResourceBackup(Arrays.asList(moment));
            searchTypeMoment.setShowTitle(true);
            list.add(searchTypeMoment);
        }

        // 遍历培训班
//        if (summary.getTrainingCourse() != null && !summary.getTrainingCourse().isEmpty()) {
//            UserResource userResource = null;
//            for (int i = 0; i < summary.getTrainingCourse().size(); i++) {
//                if (i == 4) {
//                    break;
//                }
//                userResource = summary.getTrainingCourse().get(i);
//                Moment trainingCourseMoment =  userResource != null && !ListUtil.isEmpty(userResource.getResourceBackup())?summary.getTrainingCourse().get(i).getResourceBackup().get(0):null;
//                if (trainingCourseMoment != null) {
//                    try{
//                        trainingCourseMoment.setTitle(HighLightWordUtil.highLight(trainingCourseMoment.getTitle(),keyWord));
//                    }catch (Exception e){
//
//                    }
//                    userResource.setShowTitle(i == 0);
//                    userResource.setHasMore(summary.getTrainingCourseCount() > 4);
//                    list.add(userResource);
//                }
//            }
//        } else {
//            UserResource searchTypeMoment = new UserResource();
//            Moment moment = new Moment();
//            moment.setSubject(Subject.training_course);
//            searchTypeMoment.setResourceBackup(Arrays.asList(moment));
//            searchTypeMoment.setShowTitle(true);
//            list.add(searchTypeMoment);
//        }

        // 遍历培训卡
//        if (summary.getVideoCourse() != null && !summary.getVideoCourse().isEmpty()) {
//            SearchTypeMoment searchTypeMoment = null;
//            for (int i = 0; i < summary.getVideoCourse().size(); i++) {
//                if (i == 4) {
//                    break;
//                }
//                if (summary.getVideoCourse().get(i) != null && summary.getVideoCourse().get(i).getMomentBackup() != null) {
//                    searchTypeMoment = new SearchTypeMoment();
//                    searchTypeMoment.setSubject(Subject.training_card);
//                    try{
//                        summary.getVideoCourse().get(i).getMomentBackup().setTitle(HighLightWordUtil.highLight(summary.getVideoCourse().get(i).getMomentBackup().getTitle(),keyWord));
//                    }catch (Exception e){
//
//                    }
//                    searchTypeMoment.setMoment(summary.getVideoCourse().get(i).getMomentBackup());
//                    searchTypeMoment.setShowTitle(i == 0);
//                    searchTypeMoment.setHasMore(summary.getVideoCourse().size() > 4);
//                    list.add(searchTypeMoment);
//                }
//            }
//        } else {
//            SearchTypeMoment searchTypeMoment = new SearchTypeMoment();
//            searchTypeMoment.setSubject(Subject.training_card);
//            searchTypeMoment.setShowTitle(true);
//            list.add(searchTypeMoment);
//        }

//        // 私教
//        SearchTypeMoment privateCourseSearchTypeMoment = new SearchTypeMoment();
//        privateCourseSearchTypeMoment.setSubject(Subject.private_course);// 显示titleName
//        privateCourseSearchTypeMoment.setShowTitle(true);//显示titleLayout
//        list.add(privateCourseSearchTypeMoment);

        return list;
    }


    private String getSearchValue() {
        return isEmpty(inputEt.getEditText().getText().toString().trim()) ? "" : inputEt.getEditText().getText().toString().trim();
    }

    public void showSearchResultPanel() {
        cancelLayout.expand();
        cdv.setVisibility(View.VISIBLE);
    }

    public void hideSearchResultPanel() {
        cancelLayout.collapse();
        inputEt.getEditText().clearFocus();
        KeyboardUtil.hideKeyboard(this, inputEt);
        inputEt.getEditText().setText("");
        adapter.setNewData(null);
//        cdv.setVisibility(View.INVISIBLE);
        finish();
    }

    private void doSearch(String value) {
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = value;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }


    @OnClick({R.id.tv_cancel, R.id.cancelLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
            case R.id.cancelLayout:
                hideSearchResultPanel();
                break;
        }
    }
}
